package com.hc.conferencecheck.filters;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 用于解决前端路由跳转的过滤器
 */
//@WebFilter(filterName = "routerFilter", urlPatterns = {"/*"})
public class Filter1_RouterFilter implements Filter {
    final static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(Filter1_RouterFilter.class);

    //1.使用默认的配置的httpclient
    HttpClient client = HttpClients.createDefault();
    private final String baseUrl = "http://localhost:8088";


    public void init(FilterConfig filterConfig) {
        logger.info("初始化路由过滤器");
    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        logger.info("进入路由过滤器");
        HttpServletRequest request = (HttpServletRequest) req;
        //获取请求路径
        String requestURL = request.getRequestURL().toString();

        //用户申请会议、签到、我的会议时必须先登录
        if (requestURL.contains("/apply")
                || requestURL.contains("/sign")
                || requestURL.contains("/checking")
                || requestURL.contains("/successReset")
                || requestURL.contains("/successRegister")
                || requestURL.contains("/myApply")
                || requestURL.contains("/items")
                ) {
            //如果包含指定请求路径，进行登录验证，如果验证通过就放行，否则return false;
            HttpSession session = request.getSession();
            Object user = null;
            if (requestURL.contains("/manage")) {
                //判断管理用户是否已登录
                user = session.getAttribute("adminUser");
            } else {
                user = session.getAttribute("user");
            }
            //进行跳转
            if (user == null) {
                //没有cookie,说明用户还没登录，跳转到登录页面
                HttpGet httpGet = new HttpGet(baseUrl + "login");
                client.execute(httpGet);
            } else {
                //截取最后一个斜线后面的访问路径
                String routerPath = requestURL.substring(requestURL.lastIndexOf("/"));
                String url = baseUrl + routerPath;
                HttpGet httpGet = new HttpGet(url);
                client.execute(httpGet);
            }
        }
        //其与路径放行
        chain.doFilter(req, res);
    }

    public void destroy() {
    }
}
